//
//  SalesManVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/11/6.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "SalesManVC.h"
#import "OrdinaryHomeCell.h"
#import "HNSNHeaderView.h"
#import "HNSalesManCycleDetailVC.h"
#import "HMSalesManHeadView.h"
#import "HMSalesManCell.h"
#import "ZYSalesManModel.h"
#import "HNSalesManCycleDetailDateView.h"
#import "ZYResourceSSSSController.h"
@interface SalesManVC ()<UITableViewDelegate, UITableViewDataSource,CustomAlertDelegete>
{
    NSInteger _mark;//标记类型
    NSString *_selectDate;//标记选中的日期
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic,strong) HMSalesManHeadView *headView;
@property (nonatomic,strong) NSDictionary *dict;
@property (nonatomic,copy) NSString *startTime;
@property (nonatomic,copy) NSString *endTime;
@property (nonatomic,strong) CustomDayDatePicker *datePicker;
@property (nonatomic,assign) BOOL isUp;
@end

@implementation SalesManVC


- (NSMutableArray *)dataSource {
    
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
    
}



- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    
    [self setUpSuperView];
    
    
    
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTargat:self action:@selector(rightAction) image:@"icon_pull_out" highImage:@"icon_pull_out"];
    self.navigationItem.rightBarButtonItem = rightItem;
    

    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem.customView.hidden=YES;
    
    
}



- (void)rightAction{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    //[self.navigationController popViewControllerAnimated:YES];
    
}





- (void)setNetWorkStart:(NSString *)start endTime:(NSString *)endTime{
    
    
    NSString *url;
    if (self.isUp) {
         url = [NSString stringWithFormat:@"resource.do?action=resourceMain&startTime=%@&endTime=%@",start,endTime];
       
    }else{
     url = [NSString stringWithFormat:@"resource.do?action=resourceMain&startTime=&endTime="];
       
    }
    
    
  
    
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    
    [SVProgressHUD show];
    
    
    
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
        [SVProgressHUD dismiss];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            [self.dataSource removeAllObjects];
            self.dict = [Obj valueForKey:@"t"];
            
            self.headView.dictAry = self.dict;
            
            NSArray *arr = [self.dict valueForKey:@"resources"];
            
            
            for (NSDictionary *dic in arr) {
                
                ZYSalesManModel *model = [ZYSalesManModel new];
                
                model.ID = [dic valueForKey:@"id"];
                
                
                [model setValuesForKeysWithDictionary:dic];
                
                
                
                [self.dataSource addObject:model];
                
                
                
            }
            
            [self.tableView reloadData];
            
            
            
        }
        
        
        
        
    } Fail:^(NSError *Error) {
         [SVProgressHUD dismiss];
    }];
    
    
    
    
    
    
    
    
    
    
}








- (void)setUpSuperView{
    
    
    
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
    [self.tableView registerNib:[UINib nibWithNibName:[HMSalesManCell description] bundle:nil] forCellReuseIdentifier:@"HMSalesManCellId"];
    self.headView = [[[NSBundle mainBundle]loadNibNamed:@"HMSalesManHeadView" owner:nil options:nil]lastObject];
    self.tableView.tableHeaderView = self.headView;
    
    
    self.headView.nameLabel.text = [AccountTool shareAccountTool].currentAccount.petName;

    NSString *ur = [NSString stringWithFormat:@"%@",[AccountTool shareAccountTool].currentAccount.avatar];
    
    [self.headView.peopleImageView sd_setImageWithURL:[NSURL URLWithString:ur] placeholderImage:[UIImage imageNamed:@"image_user_default"]];
    
  
    [self.headView.starSelectBtn setTitle:[NSString stringWithFormat:@"%@",[NSString yearMonthDay]] forState:(UIControlStateNormal)];
    
    [self.headView.endSelectBtn setTitle:[NSString stringWithFormat:@"%@",[NSString yearMonthDay]] forState:(UIControlStateNormal)];
    
    [self.headView.starSelectBtn addTarget:self action:@selector(allButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.endSelectBtn addTarget:self action:@selector(allButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.balanceButton addTarget:self action:@selector(allButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.headView.starSelectBtn.tag = 201;
    self.headView.endSelectBtn.tag = 202;
    self.headView.balanceButton.tag = 203;
    
    NSString *startStr = [self MgrTimeStrFormatterWitStr:[NSString yearMonthDay]];
    
    __block typeof(self) weakSelf = self;
     [self setNetWorkStart:startStr endTime:startStr];
    
    
    
    self.headView.sureBlock = ^{//确定
        
        [weakSelf sureButton];
    };
    
}


- (CustomDayDatePicker *)datePicker {
    
    if (_datePicker == nil) {
        self.datePicker = [[CustomDayDatePicker alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth - 60, 140)];
        
    }
    
    
    return _datePicker;
}


- (void)allButtonAction:(UIButton *)sender{
    
    
    NSInteger tag = sender.tag;
    
    if (201 == tag) {
        
        
        JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 60, 200)];
        alert.center = self.view.center;
        alert.delegate = self;
        [alert initwithtitle:@"开始时间" andcommitbtn:@"确定" andStr:@"0"];
        [alert addSubview:self.datePicker];
        [alert show];
        
        
        _mark = 1;
        
//        [[UIApplication sharedApplication].keyWindow addSubview:[[HNSalesManCycleDetailDateView alloc]initWithCurrentDate:nil Title:@"开始时间" Min:2017 Max:2050 Complete:^(NSString *DateStr) {
//
//            [self.headView.starSelectBtn setTitle:[NSString stringWithFormat:@" %@",DateStr] forState:(UIControlStateNormal)];
//
//        } ]];
        
        
        
        
        
        
    }else if (202 == tag){
        
        JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 60, 200)];
        alert.center = self.view.center;
        alert.delegate = self;
        [alert initwithtitle:@"结束时间" andcommitbtn:@"确定" andStr:@"0"];
        [alert addSubview:self.datePicker];
        [alert show];
        
        
        _mark = 2;
        
        
//        [[UIApplication sharedApplication].keyWindow addSubview:[[HNSalesManCycleDetailDateView alloc]initWithCurrentDate:nil Title:@"结束时间" Min:2017 Max:2050 Complete:^(NSString *DateStr) {
//
//            [self.headView.endSelectBtn setTitle:[NSString stringWithFormat:@" %@",DateStr] forState:(UIControlStateNormal)];
//
//        } ]];
    
        
        
    }else{
        
        
        
        ZYResourceSSSSController *vc = [ZYResourceSSSSController new];
        
        vc.ID = [AccountTool shareAccountTool].currentAccount.uid;
        
        [self.navigationController pushViewController:vc animated:YES];
        
        
        
        
        
    }
    
    
    
    
    
    
}




- (void)btnindex:(int)index :(int)tag{
    
    if (index == 2) {
        if (_mark == 1) {
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
        [self.headView.starSelectBtn setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
        }else if (_mark == 2){
            
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
            [self.headView.endSelectBtn setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
        }
    }
    
    
    
    
}





- (void)sureButton{
    
    
    self.isUp = YES;
    
    NSComparisonResult result = [self.headView.starSelectBtn.currentTitle compare:self.headView.endSelectBtn.currentTitle];
    
    if (result != NSOrderedAscending) {
        [SVProgressHUD showErrorWithStatus:@"结束时间必须大于开始时间!"];
    }else{
        
                NSString *start = [self.headView.starSelectBtn.currentTitle stringByReplacingOccurrencesOfString:@" " withString:@""];
        
                NSString *endSelect = [self.headView.endSelectBtn.currentTitle stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        
                [self setSetTowSureStart:[self MgrTimeStrFormatterWitStr:start] endSelect:[self MgrTimeStrFormatterWitStr:endSelect]];
        
    }
    
    
    
    
//    if (![self JudgeBigOrSmallWithBegin:self.headView.starSelectBtn.currentTitle End:self.headView.endSelectBtn.currentTitle]) {
//
//        [SVProgressHUD showErrorWithStatus:@"结束时间必须大于开始时间!"];
//    } else {
//        // 发起时间查询的请求
//
//
//        NSString *start = [self.headView.starSelectBtn.currentTitle stringByReplacingOccurrencesOfString:@" " withString:@""];
//
//        NSString *endSelect = [self.headView.endSelectBtn.currentTitle stringByReplacingOccurrencesOfString:@" " withString:@""];
//
//
//        [self setSetTowSureStart:[self MgrTimeStrFormatterWitStr:start] endSelect:[self MgrTimeStrFormatterWitStr:endSelect]];
//
//
//    }
    
}
- (void)setSetTowSureStart:(NSString *)startStr endSelect:(NSString *)endSelect{
    
    
    self.startTime = startStr;
    self.endTime = endSelect;
    //    self.isSure = YES;
    //    self.isSearch = NO;
    
   
    [self setNetWorkStart:self.startTime endTime:self.endTime];
    
    
    
    
}


#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HMSalesManCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"HMSalesManCellId" forIndexPath:indexPath];
    Cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZYSalesManModel *model = self.dataSource[indexPath.row];
    
    [Cell assignByZYSalesManModel:model];
    
    
    return Cell;
}

////区头
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    HNSNHeaderView *HeaderView = [[[NSBundle mainBundle] loadNibNamed:[HNSNHeaderView description] owner:nil options:nil] lastObject];
//    
//    if (self.isSupermanager == NO) {
//    
//  //业务员
//        HeaderView.HeaderName.text = [NSString stringWithFormat:@"%@(%@)",[AccountTool shareAccountTool].currentAccount.websiteName,[AccountTool shareAccountTool].currentAccount.petName];
//        [HeaderView RefreshData:[AccountTool shareAccountTool].currentAccount.picture];
//
//    }
//    
//    return HeaderView;
//}
//
////区高
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 150 * KScale;
//}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

//单击行事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 处理TableView的点击事件
//    if (indexPath.row == 0) {
        // 详情
        ZYSalesManModel *model = [self.dataSource objectAtIndex:indexPath.row];
        HNSalesManCycleDetailVC *VC = [[HNSalesManCycleDetailVC alloc] init];
        VC.ResourceId = @([model.ID integerValue]);
        [self.navigationController pushViewController:VC animated:YES];
//    }
}


/** 将2017年10月的格式转成2017-10 */
- (NSString *)MgrTimeStrFormatterWitStr:(NSString *)Str {
    
    Str = [Str stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
    Str = [Str stringByReplacingOccurrencesOfString:@"月" withString:@""];
    return Str;
}



/** 判断结束时间是不要大于开始时间 */
- (BOOL)JudgeBigOrSmallWithBegin:(NSString *)Begin End:(NSString *)End {
    
    NSArray *BeginArr = [Begin componentsSeparatedByString:@"年"];
    NSString *BeginMouths = [[BeginArr lastObject] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    NSArray *EndArr = [End componentsSeparatedByString:@"年"];
    NSString *EndMouths = [[EndArr lastObject] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    NSInteger BeginYear = [[BeginArr firstObject] integerValue];
    NSInteger BeginMouth = [BeginMouths integerValue];
    NSInteger EndYear = [[EndArr firstObject] integerValue];
    NSInteger EndMouth = [EndMouths integerValue];
    if (EndYear - BeginYear > 0) {
        
        return YES;
    }
    else if (EndYear - BeginYear == 0 && EndMouth - BeginMouth >= 0) {
        
        return YES;
    } else {
        
        return NO;
    }
}


@end
